﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using VirtualTournaments.DataAccess.SqlServer.DataMappers;

namespace VirtualTournaments.DataAccess.SqlServer.DataProxies
{
	internal sealed class StandingsDataProxy : Business.Tournaments.Standings
	{
		private IDataProxy<SqlServer.Tournament> _dataProxy;

		internal StandingsDataProxy(IDataProxy<SqlServer.Tournament> dataProxy)
			: base(null)
		{
			this._dataProxy = dataProxy;
		}

		#region Override properties

		internal bool TeamsListHasBeenRead { get; set; }
		protected override List<Business.Tournaments.TeamStatics> TeamsList
		{
			get
			{
				if (!TeamsListHasBeenRead)
				{
					TeamsListHasBeenRead = true;
					if (base.TeamsList == null)
					{
						base.TeamsList = MapTeamsList();
					}
				}
				return base.TeamsList;
			}
		}

		internal bool TeamsMapHasBeenRead { get; set; }
		protected override Dictionary<string, Business.Tournaments.TeamStatics> TeamsMap
		{
			get
			{
				if (!TeamsMapHasBeenRead)
				{
					TeamsMapHasBeenRead = true;
					if (base.TeamsMap == null)
					{
						base.TeamsMap = MapTeamsMap();
					}
				}
				return base.TeamsMap;
			}
		}

		#endregion

		#region Mapping methods

		private List<Business.Tournaments.TeamStatics> MapTeamsList()
		{
			return _dataProxy.InnerDataObject.Standings.Select(standings =>
				{
					TeamStaticsDataProxy teamStatics = new TeamStaticsDataProxy(TeamsDataMapper.Instance.DataObject2BusinessObject(standings.Team));
					teamStatics.SetDrawMatches(standings.DrawMatches);
					teamStatics.SetGoalsAgainst(standings.GoalsAgainst);
					teamStatics.SetGoalsDifference(standings.GoalsAgainst);
					teamStatics.SetGoalsFor(standings.GoalsFor);
					teamStatics.SetLostMatches(standings.LostMatches);
					teamStatics.SetPlayedMatches(standings.PlayedMatches);
					teamStatics.SetPoints(standings.Points);
					teamStatics.SetWonMatches(standings.WonMatches);
					return teamStatics;
				}
			).Cast<Business.Tournaments.TeamStatics>().ToList();
		}

		private Dictionary<string, Business.Tournaments.TeamStatics> MapTeamsMap()
		{
			return MapTeamsList().ToDictionary(teamStatics => teamStatics.Team.Name);
		}

		#endregion
	}
}
